package com.spice.im.chat;

import java.text.DecimalFormat;
import java.util.ArrayList;




import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jivesoftware.smack.util.StringUtils;














//import com.byl.qrobot.util.ExpressionUtil;
import com.dodola.model.DuitangInfo;
import com.dodola.model.DuitangInfoAdapter;
import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.spice.im.EmoticonsTextView;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
import com.spice.im.SimpleListDialog;
import com.spice.im.SimpleListDialogAdapter;
import com.spice.im.SimpleListDialog.onSimpleListItemClickListener;
import com.spice.im.chat.ChatPullRefListActivity.StaggeredAdapter;
import com.spice.im.chat.MessageText.MESSAGE_TYPE;
import com.spice.im.group.GroupDetailsActivity;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.ImageFetcher;
import com.spiceim.db.TContactGroup;
import com.spiceim.db.TContactGroupAdapter;
import com.stb.isharemessage.service.XmppConnectionAdapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.ClipboardManager;
import android.text.SpannableString;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class CardMessageItem implements OnLongClickListener,OnClickListener{
	private static final String TAG = "CardMessageItem > DeleteMessage";
	private MessageText mMsgText;
	protected Context mContext;
	private MESSAGE_TYPE messageType;
	protected LayoutInflater mInflater;
	protected LinearLayout mLayoutMessageContainer;
	protected View mRootView;
	protected int mBackground;
//	private HandyTextView mEtvContent;
//	private EmoticonsTextView mEtvContent;
	private FlowView news_pic;//头像
	private HandyTextView user_item_htv_name;//用户或群组名称
	private HandyTextView user_item_htv_sign;//用户或群组JID号
	private HandyTextView user_item_htv_sign2;//标识为“个人名片”或“群组名片”
	
	private String invite_type = "";//邀请类型：群组group , 或个人personal
	private String invite_from = "";//邀请人
	private String invite_subject = "";//邀请标题
	private String invite_tagid = "";//群组id或添加好友请求时为uid
	private String invite_tagname = "";//群组名称或好友名称
	private String invite_tagimg = "";//群组头像或添加好友时邀请人头像
	
	private LinearLayout mLayoutLeftContainer;
	private FlowView mIvPhotoView;
	private HandyTextView message_tv_timestamp;//消息发送/接收时间
	private HandyTextView message_tv_nickname;
	private String headimg = "",myheadimg = "";
	private ImageFetcher mImageFetcher;
	private HandyTextView message_tv_status_audio = null;//消息发送状态
	private ChatPullRefListActivity mActivity = null;
	private String username = "",myusername = "";
	
	private int mPosition;
	private StaggeredAdapter mStAdapter = null;
	
	private String fromAccount;
	private String toAccount;
	
	
	private DuitangInfo duitangInfo = null;
	private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
	private TContactGroupAdapter tContactGroupAdapter = null;
	private SimpleListDialog mDialog = null;
	private MessageAdapter messageAdapter = null;//删除本地数据库用户聊天记录
	private TContactGroup tg = null;
	
	public CardMessageItem(Context context,
			MessageText msgText,
			int position,
			StaggeredAdapter stAdapter,
			String _fromAccount,
			String _toAccount,
			String _headimg,
			String _myheadimg,
			ChatPullRefListActivity activity,
			String _username,
			String _myusername){
//		super(bareJid, name, message, isError,date);
		mMsgText = msgText;
		mContext = context;
		mPosition = position;
		mStAdapter = stAdapter;
		fromAccount = _fromAccount;
		toAccount = _toAccount;
		headimg = _headimg;
		myheadimg = _myheadimg;
		mActivity = activity;
		username = _username;
		myusername = _myusername;
		
		duitangInfoAdapter = DuitangInfoAdapter.getInstance(mContext);
		tContactGroupAdapter = TContactGroupAdapter.getInstance(mContext);
		messageType = mMsgText.getMessageType();
		
//		mMsgText.getBareJid();
//		mMsgText.getMTo();
//		Log.e("※※※※※20141020※※※※※", "※※消息TextMessageItem=>mMsgText.getBareJid()="
//				+mMsgText.getBareJid()
//				+";mMsgText.getMTo()="
//				+mMsgText.getMTo()
//				+";fromAccount="
//				+fromAccount
//				+";toAccount="
//				+toAccount
//				+";messageType="
//				+messageType);
		initNameImg();
		
		//20121224 start
		messageAdapter = MessageAdapter.getInstance(mContext);
		mLoadingDialog = new FlippingLoadingDialog(mContext, "请求提交中");
		String[] codes = new String[] { "复制","删除","转发" };//分享,翻译
		mDialog = new SimpleListDialog(context);
		mDialog.setTitle("提示");
		mDialog.setTitleLineVisibility(View.GONE);
		mDialog.setAdapter(new SimpleListDialogAdapter(context, codes));
		mDialog.setOnSimpleListItemClickListener(new OnReplyDialogItemClickListener(
				));
		//20141224 end
		
		mInflater = LayoutInflater.from(context);
		switch (messageType) {
		case RECEIVER:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_to_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_send;
			//message_send_template.xml
			mRootView = mInflater.inflate(R.layout.message_send_template,
					null);
			mBackground = R.drawable.bg_message_box_send;
			break;

		case SEND:
//			mRootView = mInflater.inflate(R.layout.specialchatting_item_from_picture,
//					null);
////			mBackground = R.drawable.bg_message_box_receive;
			//message_receive_template.xml
			mRootView = mInflater.inflate(R.layout.message_receive_template,
					null);
			mBackground = R.drawable.bg_message_box_receive;
			message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			break;
		case conference:
//			//message_send_template.xml
//			mRootView = mInflater.inflate(R.layout.message_send_template,
//					null);
//			mBackground = R.drawable.bg_message_box_send;
			if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
				mRootView = mInflater.inflate(R.layout.message_receive_template,
						null);
				mBackground = R.drawable.bg_message_box_receive;
				message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
				String key2 = StringUtils.parseName(fromAccount);
				if(key.equals(key2)){//自己发给群
					mRootView = mInflater.inflate(R.layout.message_receive_template,
							null);
					mBackground = R.drawable.bg_message_box_receive;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}else{
					//message_send_template.xml
					mRootView = mInflater.inflate(R.layout.message_send_template,
							null);
					mBackground = R.drawable.bg_message_box_send;
					message_tv_status_audio = (HandyTextView)mRootView.findViewById(R.id.message_tv_status_audio);
				}
			}
			break;
		}
		Log.e("※※※※※####20170731####※※※※※", "※※msgText.getMessage()※※"+msgText.getMessage());
		//String news = "<invite type='group' from='"+"uid"+"@0/"+"username"+"' subject='"+"uid"+"@0/"+"username"+"邀请你加入群组' tagid='"+"tagid"+"' tagname='"+"tagname"+"' tagimg='"+"tagimg"+"'>群组邀请信息</invite>";
		if(msgText.getMessage().startsWith("<invite type=")){//邀请
			Log.e("※※※※※####20170731####※※※※※", "※※msgText.getMessage()2※※"+msgText.getMessage());
            // 首先匹配img标签内的内容
            String img_regex = "<(?i)invite(.*?)>(.*?)</(?i)invite>";//invite 信息
//			String img_regex = "<(?i)invite(.*?)></(?i)invite>";//invite 信息
            Pattern p = Pattern.compile(img_regex);
            Matcher m = p.matcher(msgText.getMessage());
            
            String label_attribute;//标签中的所有属性attribute   即本例中 从 type='group'一直到tagname='tagname'整个字符串
            String laben_value;//<invite>值域</invite>
            
            while(m.find()){

            	label_attribute=m.group(1);
                laben_value=m.group(2);
                System.out.println("src_alt="+label_attribute);
                System.out.println("img_name="+laben_value);
                if(null==label_attribute && null==laben_value){
                    continue;
                }
                
                // 匹配type中的内容
                String type_reg = "type=\'(.*?)\'";//src
                Pattern type_p = Pattern.compile(type_reg);
                Matcher type_m = type_p.matcher(label_attribute);
                while(type_m.find()){
                	invite_type = type_m.group(1);
                    System.out.println("type是：" + invite_type);
                    Log.e("※※※※※####20170731####※※※※※", "※※invite_type※※"+invite_type);
                }
                
                // 匹配from中的内容
                String from_reg = "from=\'(.*?)\'";//alt
                Pattern from_p = Pattern.compile(from_reg);
                Matcher from_m = from_p.matcher(label_attribute);
                while(from_m.find()){
                	invite_from = from_m.group(1);
                	System.out.println("from是：" +invite_from);
                	Log.e("※※※※※####20170731####※※※※※", "※※invite_from※※"+invite_from);

                }       
                
                // 匹配subject中的内容
                String subject_reg = "subject=\'(.*?)\'";//alt
                Pattern subject_p = Pattern.compile(subject_reg);
                Matcher subject_m = subject_p.matcher(label_attribute);
                while(subject_m.find()){
                	invite_subject = subject_m.group(1);
                	System.out.println("subject是：" +invite_subject );
                	Log.e("※※※※※####20170731####※※※※※", "※※invite_subject※※"+invite_subject);

                } 

                // 匹配tagid中的内容
                String tagid_reg = "tagid=\'(.*?)\'";//alt
                Pattern tagid_p = Pattern.compile(tagid_reg);
                Matcher tagid_m = tagid_p.matcher(label_attribute);
                while(tagid_m.find()){
                	invite_tagid = tagid_m.group(1);
                	System.out.println("tagid是：" +invite_tagid );
                	Log.e("※※※※※####20170731####※※※※※", "※※invite_tagid※※"+invite_tagid);

                } 
                
                // 匹配tagname中的内容
                String tagname_reg = "tagname=\'(.*?)\'";//alt
                Pattern tagname_p = Pattern.compile(tagname_reg);
                Matcher tagname_m = tagname_p.matcher(label_attribute);
                while(tagname_m.find()){
                	invite_tagname = tagname_m.group(1);
                	System.out.println("tagname是：" +invite_tagname );
                	Log.e("※※※※※####20170731####※※※※※", "※※invite_tagname※※"+invite_tagname);

                } 

                // 匹配tagimg中的内容
                String tagimg_reg = "tagimg=\'(.*?)\'";//alt
                Pattern tagimg_p = Pattern.compile(tagimg_reg);
                Matcher tagimg_m = tagimg_p.matcher(label_attribute);
                while(tagimg_m.find()){
                	invite_tagimg = tagimg_m.group(1);
                	System.out.println("tagimg是：" +invite_tagimg );
                	Log.e("※※※※※####20170731####※※※※※", "※※invite_tagimg※※"+invite_tagimg);

                } 
            }
            
		}
		
		
//		if (mRootView != null) {
		mLayoutMessageContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_messagecontainer);
		mLayoutMessageContainer.setBackgroundResource(mBackground);
		
		mLayoutLeftContainer = (LinearLayout) mRootView
		.findViewById(R.id.message_layout_leftcontainer);
		mIvPhotoView = (FlowView) mRootView.findViewById(R.id.message_iv_userphoto);
		
		message_tv_timestamp = (HandyTextView)mRootView.findViewById(R.id.message_tv_timestamp);
		message_tv_nickname = (HandyTextView)mRootView.findViewById(R.id.message_tv_nickname);
		
		
		onInitViews();
//		}
	}
    private RelativeLayout user_item_relative;
	protected void onInitViews() {
		View view = mInflater.inflate(R.layout.message_card, null);
		mLayoutMessageContainer.addView(view);
//		mEtvContent = (EmoticonsTextView) view
//				.findViewById(R.id.message_etv_msgtext);
		news_pic = (FlowView) view
				.findViewById(R.id.news_pic);
		user_item_htv_name = (HandyTextView)view
				.findViewById(R.id.user_item_htv_name);//用户或群组名称
		user_item_htv_sign = (HandyTextView)view
				.findViewById(R.id.user_item_htv_sign);//用户或群组JID号
		user_item_htv_sign2 = (HandyTextView)view
		.findViewById(R.id.user_item_htv_sign2);//标识为“个人名片”或“群组名片”
		user_item_relative = (RelativeLayout)view.findViewById(R.id.user_item_relative);
		user_item_relative.setOnClickListener(this);
//		String zhengze = "f0[0-9]{2}|f10[0-7]";											//正则表达式，用来判断消息内是否有表情
//		try {
//			SpannableString spannableString = ExpressionUtil.getExpressionString(mContext, mMsgText.getMessage(), zhengze);
////			holder.contentView.setText(spannableString);
//			mEtvContent.setText(spannableString);
//		} catch (NumberFormatException e) {
//			e.printStackTrace();
//		} catch (SecurityException e) {
//			e.printStackTrace();
//		} catch (IllegalArgumentException e) {
//			e.printStackTrace();
//		}
		if(mMsgText.getIsOffline()==2){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.VISIBLE);
			
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_failure2);
		    	message_tv_status_audio.setText("发送失败");
		    }
		}else if(mMsgText.getIsOffline()==1){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.GONE);
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
		    	message_tv_status_audio.setText("送达");
		    }
		}
		else if(mMsgText.getIsOffline()==0){
//			mRootView.findViewById(R.id.isOfflineMsg).setVisibility(View.GONE);
		    if(message_tv_status_audio!=null){
		    	message_tv_status_audio.setBackgroundResource(R.drawable.bg_msgbox_state_read2);
		    	message_tv_status_audio.setText("发送中");
		    }
		}
////		mEtvContent.setText(mMsgText.getMessage());
//		mEtvContent.setText(ExpressionUtil.prase(mContext, mEtvContent, mMsgText.getMessage()));
//		mEtvContent.setOnLongClickListener(this);
//		user_item_htv_name.setText(invite_tagname!=null?invite_tagname:invite_subject);
//		user_item_htv_name.setText("测试"+invite_subject);
		if(invite_type.equalsIgnoreCase("friend"))//personal
			user_item_htv_name.setText(invite_from);
		else
			user_item_htv_name.setText(invite_tagname);
		if(invite_type.equalsIgnoreCase("friend"))//personal
			user_item_htv_sign.setText("用户ID号:"+invite_from+",请求加你为好友.");
		else
			user_item_htv_sign.setText("群组ID号:"+invite_tagid+","+invite_from+"邀请你加入群组.");
		
		if(invite_type.equalsIgnoreCase("friend"))//personal
			user_item_htv_sign2.setText("个人名片");
		else
			user_item_htv_sign2.setText("群组名片");//group
		
		mLayoutMessageContainer.setOnLongClickListener(this);
		
		
        mImageFetcher = new ImageFetcher(mContext, 77);
        mImageFetcher.setUListype(0);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo3);
        mImageFetcher.setExitTasksEarly(false);
        
//        mImageFetcher.loadRoundImage(invite_tagimg, news_pic,mHandler);
//        mImageFetcher.loadImage(invite_tagimg.replace("http://localhost:8080/javacenterhome/", XmppConnectionAdapter.downloadPrefix), news_pic);
        mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+invite_tagimg , news_pic);
		mHandler.sendEmptyMessage(0);//?
	}
	String headpath = "";
	protected void onFillMessage() {
		
		mLayoutLeftContainer.setVisibility(View.VISIBLE);
////		mIvPhotoView.setImageBitmap();
////		mIvPhotoView.setImageResource(R.drawable.head);
//		switch (messageType) {
//			case RECEIVER:
//				mImageFetcher.loadImage(headimg, mIvPhotoView);
//				break;
//			case SEND:
//				mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//				break;
//		
//		}
//		
//		message_tv_timestamp.setText(mMsgText.getTimestamp().toLocaleString());
		
		switch (messageType) {
		case RECEIVER:
//			mImageFetcher.loadImage(headimg, mIvPhotoView);
//			message_tv_nickname.setText(username);
			if(mMsgText.getBareJid().indexOf("@1")==-1){
//        		try{
//        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
//        		
//				if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//				else
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//				
				
				tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
				if(tg!=null){
					headpath = tg.getAvatarPath();
					if(tg.getName()!=null && tg.getName().length()!=0)
						message_tv_nickname.setText(tg.getName());
					else
						message_tv_nickname.setText(tg.getUsername());
				}else{
					headpath = "";
					message_tv_nickname.setText(mMsgText.getBareJid());
				}
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
				
//        		try{
//        			headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
////				message_tv_nickname.setText("uid为"+key);
////				message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//				if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//				else
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
				
				tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
				if(tg!=null){
					headpath = tg.getAvatarPath();
					if(tg.getName()!=null && tg.getName().length()!=0)
						message_tv_nickname.setText(tg.getName());
					else
						message_tv_nickname.setText(tg.getUsername());
				}else{
					headpath = "";
					message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
				}
			}
			mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
			break;
		case SEND:
//			mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//			message_tv_nickname.setText(myusername);
			if(mMsgText.getBareJid().indexOf("@1")==-1){
//				try{
//					headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
//				if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//				if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName().length()!=0)
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
//				else
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getUsername());
//				}else
//					message_tv_nickname.setText("空"+StringUtils.parseBareAddress(mMsgText.getBareJid()));
//				
				
				tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
				if(tg!=null){
					headpath = tg.getAvatarPath();
					if(tg.getName()!=null && tg.getName().length()!=0)
						message_tv_nickname.setText(tg.getName());
					else
						message_tv_nickname.setText(tg.getUsername());
				}else{
					headpath = "";
					message_tv_nickname.setText(mMsgText.getBareJid());
				}
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
//				try{
//					headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
////				message_tv_nickname.setText("uid为"+key);
////				message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress("2@0")).getName());
//				if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//				else
//					message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//				
				
				tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
				if(tg!=null){
					headpath = tg.getAvatarPath();
					if(tg.getName()!=null && tg.getName().length()!=0)
						message_tv_nickname.setText(tg.getName());
					else
						message_tv_nickname.setText(tg.getUsername());
				}else{
					headpath = "";
					message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
				}
			}
			mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
			break;
		case conference:
			Log.e("※※※※※2014080508050805※※※※※", "※※fromAccount="+fromAccount+";toAccount="+toAccount);
//			if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
//				mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//				message_tv_nickname.setText(myusername);
//			}else{
//				String key = StringUtils.parseResource(mMsgText.getBareJid());
//				if(key.startsWith("/"))
//					key = key.substring(1);//"/18901203590"
//				String key2 = StringUtils.parseName(fromAccount);
//				if(key.equals(key2)){//自己发给群
//					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
//					message_tv_nickname.setText(myusername);
//				}else{
////					Contact contact = mActivity.mListContact.get(key);
////					String url = "";
////					if(contact!=null){
////						message_tv_nickname.setText(contact.getName());
////			            if(contact.getAvatarId()!=null 
////			            		&& contact.getAvatarId().length()!=0 
////			            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////			            		&& (
////			            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////			            			))
////			            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////			            if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
////					}else{
//						mImageFetcher.loadImage(headimg, mIvPhotoView);
//						message_tv_nickname.setText(username);
////					}
////					if(url!=null && url.length()!=0)
////						mImageFetcher.loadImage(url, mIvPhotoView);
//				}
//			}
			if(mMsgText.getBareJid().indexOf("@1")==-1){//自己发给群
////				mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////				message_tv_nickname.setText(myusername);
//				try{
//					headpath = "data/avatar/"+avatar_file(Integer.parseInt(StringUtils.parseName(mMsgText.getBareJid())),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
//				message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid())).getName());
				
				tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()));
				if(tg!=null){
					headpath = tg.getAvatarPath();
					if(tg.getName()!=null && tg.getName().length()!=0)
						message_tv_nickname.setText(tg.getName());
					else
						message_tv_nickname.setText(tg.getUsername());
				}else{
					headpath = "";
					message_tv_nickname.setText(mMsgText.getBareJid());
				}
			}else{
				String key = StringUtils.parseResource(mMsgText.getBareJid());
				if(key.startsWith("/"))
					key = key.substring(1);//"/18901203590"
//				try{
//					headpath = "data/avatar/"+avatar_file(Integer.parseInt(key),"middle","");
//        		}catch(Exception e){
//        			e.printStackTrace();
//        		}
				String key2 = StringUtils.parseName(fromAccount);
				if(key.equals(key2)){//自己发给群
////					mImageFetcher.loadImage(myheadimg, mIvPhotoView);
////					message_tv_nickname.setText(myusername);
////					message_tv_nickname.setText("uid为"+key);
//					if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0)
//						message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());//bug 需要登录成功后将自己的信息存入本地数据库
//					else
//						message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0)
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
					
				}else{
////					Contact contact = mActivity.mListContact.get(key);
////					String url = "";
////					if(contact!=null){
////						message_tv_nickname.setText(contact.getName());
////			            if(contact.getAvatarId()!=null 
////			            		&& contact.getAvatarId().length()!=0 
////			            		&& !contact.getAvatarId().equalsIgnoreCase("null")
////			            		&& (
////			            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
////			            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
////			            			))
////			            	url = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJID())+"/"+"thumbnail_"+contact.getAvatarId();
////			            if(url!=null && url.length()!=0)
////							mImageFetcher.loadImage(url, mIvPhotoView);
////					}else{
////						mImageFetcher.loadImage(headimg, mIvPhotoView);
////						message_tv_nickname.setText(username);
//						if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"))!=null){
//								if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName()!=null
//								&& tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().length()!=0
//								&& !tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName().equalsIgnoreCase("null"))
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getName());
//						else
//							message_tv_nickname.setText(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0")).getUsername());
//						}else
//							message_tv_nickname.setText(key+"@0");
////						message_tv_nickname.setText(key);
////					}
////					if(url!=null && url.length()!=0)
////						mImageFetcher.loadImage(url, mIvPhotoView);
					
					tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(key+"@0"));
					if(tg!=null){
						headpath = tg.getAvatarPath();
						if(tg.getName()!=null && tg.getName().length()!=0 && !tg.getName().equalsIgnoreCase("null"))
							message_tv_nickname.setText(tg.getName());
						else
							message_tv_nickname.setText(tg.getUsername());
					}else{
						headpath = "";
						message_tv_nickname.setText(StringUtils.parseBareAddress(key+"@0"));//"空"+
					}
				}
			}
			mImageFetcher.loadImage(XmppConnectionAdapter.downloadPrefix+headpath, mIvPhotoView);
			break;
	
		}
	
		message_tv_timestamp.setText(mMsgText.getTimestamp().toLocaleString());
	}
	public View getRootView() {
		return mRootView;
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.user_item_relative:
//				Toast.makeText(mContext, "单击000：CardMessageItem", Toast.LENGTH_SHORT).show();
//				Toast.makeText(mContext, "单击111：CardMessageItem", Toast.LENGTH_SHORT).show();
				
				Intent intent = null;
				if(invite_type.equalsIgnoreCase("group")){
					intent = new Intent(mContext, GroupDetailsActivity.class);//GroupProfileActivity.class multiuserlistmain.class
	//		    	Toast.makeText(context, "单击roomname：" + StringUtils.parseName(get_url()), Toast.LENGTH_SHORT).show();
			    	intent.putExtra("groupId", invite_tagid);
			    	intent.putExtra("groupName",invite_tagname);
			    	intent.putExtra("tagimg", invite_tagimg);
			    	intent.putExtra("invitetag", "0");//代表被邀请
				}else if(invite_type.equalsIgnoreCase("friend")){
					intent = new Intent(mContext, OtherProfileActivity.class);
		        	intent.putExtra("searchkey",StringUtils.parseResource(invite_from));
				}
		    	mContext.startActivity(intent);
				break;
			default:
				break;
		}
	}
	@Override
	public boolean onLongClick(View v) {
//		System.out.println("长按");
//		return true;
		if(mDialog!=null)
			mDialog.show();
		return true;
	}
	
	public void initNameImg(){
		switch (messageType) {
			case RECEIVER:
				if(headimg==null
						|| headimg.equalsIgnoreCase("null")
						|| headimg.length()==0
						|| username==null
						|| username.equalsIgnoreCase("null")
						|| username.length()==0){
					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));//toAccount
					if(duitangInfo!=null){
						headimg = duitangInfo.getIsrc();
						username = duitangInfo.getName();
					}else{
						headimg = "";
						username = StringUtils.parseName(mMsgText.getBareJid());
					}
				}
//				if(myheadimg==null
//						|| myheadimg.equalsIgnoreCase("null")
//						|| myheadimg.length()==0
//						|| myusername==null
//						|| myusername.equalsIgnoreCase("null")
//						|| myusername.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						myheadimg = duitangInfo.getIsrc();
//						myusername = duitangInfo.getName();
//					}else{
//						myheadimg = "";
//						myusername = StringUtils.parseName(fromAccount);
//					}
//				}
				break;
			case SEND:
//				if(headimg==null
//						|| headimg.equalsIgnoreCase("null")
//						|| headimg.length()==0
//						|| username==null
//						|| username.equalsIgnoreCase("null")
//						|| username.length()==0){
//					duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
//					if(duitangInfo!=null){
//						headimg = duitangInfo.getIsrc();
//						username = duitangInfo.getName();
//					}else{
//						headimg = "";
//						username = StringUtils.parseName(fromAccount);
//					}
//				}
				if(myheadimg==null
						|| myheadimg.equalsIgnoreCase("null")
						|| myheadimg.length()==0
						|| myusername==null
						|| myusername.equalsIgnoreCase("null")
						|| myusername.length()==0){
					if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
					else
						duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
					if(duitangInfo!=null){
						myheadimg = duitangInfo.getIsrc();
						myusername = duitangInfo.getName();
					}else{
						myheadimg = "";
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							myusername = StringUtils.parseName(fromAccount);
						else
							myusername = StringUtils.parseName(mMsgText.getBareJid());//toAccount
					}
				}
				break;
			case conference:
				if(mMsgText.getBareJid().indexOf("@conference.")==-1){//自己发给群
					if(myheadimg==null
							|| myheadimg.equalsIgnoreCase("null")
							|| myheadimg.length()==0
							|| myusername==null
							|| myusername.equalsIgnoreCase("null")
							|| myusername.length()==0){
						if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(fromAccount));
						else
							duitangInfo = duitangInfoAdapter.getDuitangInfo(StringUtils.parseName(mMsgText.getBareJid()));
						if(duitangInfo!=null){
							myheadimg = duitangInfo.getIsrc();
							myusername = duitangInfo.getName();
						}else{
							myheadimg = "";
							if(mMsgText.getBareJid().equalsIgnoreCase("Me"))
								myusername = StringUtils.parseName(fromAccount);
							else
								myusername = StringUtils.parseName(mMsgText.getBareJid());
						}
					}
				}else{
					String key = StringUtils.parseResource(mMsgText.getBareJid());
					if(key.startsWith("/"))
						key = key.substring(1);//"/18901203590"
					String key2 = StringUtils.parseName(fromAccount);
					if(key.equals(key2)){//自己发给群
						if(myheadimg==null
								|| myheadimg.equalsIgnoreCase("null")
								|| myheadimg.length()==0
								|| myusername==null
								|| myusername.equalsIgnoreCase("null")
								|| myusername.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								myheadimg = duitangInfo.getIsrc();
								myusername = duitangInfo.getName();
							}else{
								myheadimg = "";
								myusername = key;
							}
						}
					}else{
						//message_send_template.xml
						if(headimg==null
								|| headimg.equalsIgnoreCase("null")
								|| headimg.length()==0
								|| username==null
								|| username.equalsIgnoreCase("null")
								|| username.length()==0){
							duitangInfo = duitangInfoAdapter.getDuitangInfo(key);
							if(duitangInfo!=null){
								headimg = duitangInfo.getIsrc();
								username = duitangInfo.getName();
							}else{
								headimg = "";
								username = key;
							}
						}
					}
				}
				
//				Log.e("※※※※※20141020※※※※※", "※※消息TextMessageItem=>mMsgText.getBareJid()="
//						+mMsgText.getBareJid()
//						+";mMsgText.getMTo()="
//						+mMsgText.getMTo()
//						+";key="
//						+StringUtils.parseResource(mMsgText.getBareJid())
//						+";key2="
//						+StringUtils.parseName(fromAccount));
				break;
			default:
				break;
		
		}
	}
	
	
	private class OnReplyDialogItemClickListener implements
	onSimpleListItemClickListener {
		
		public OnReplyDialogItemClickListener() {
		}
		@Override
		public void onItemClick(int position) {
			// "复制","删除","转发" };//分享,翻译
			switch (position) {
				case 0:
					copy(mMsgText.getMessage());
					break;
				case 1:
					startDelete();
					break;
				case 2:
//					ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//					m.setText(mMsgText.getMessage());
//		        	Intent intent = new Intent(mContext, BulkMsgContactListPullRefListActivity.class);//BulkMsgContactListPullRefListActivity
//		        	intent.putExtra("myheadimg", myheadimg);
//		        	intent.putExtra("myusername", myusername);
//		        	
//		        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		        	mContext.startActivity(intent);
//		        	if(mActivity != null)
//		        		((ChatPullRefListActivity)mContext).finish();
//		        	else if(mActivity_bulkmsg !=null)
//		        		((BulkMsgChatPullRefListActivity)mContext).finish();
					break;
			}
		}
	}
	private void copy(String text) {
		ClipboardManager m = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
		m.setText(text);
		showCustomToast("已成功复制文本:"+text);
	}
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(mContext).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(mContext);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected FlippingLoadingDialog mLoadingDialog;
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
//		mAsyncTasks.add(asyncTask.execute());
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}

	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
	private void startDelete() {
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在删除,请稍候...");
				Log.e("MMMMMMMMMMMM20141224DeleteMessageMMMMMMMMMMMM", "++++++++++++++20141224DeleteMessage="+mMsgText.getId());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
				    messageAdapter.deleteMessage(mMsgText.getId());
				} catch (Exception e) {
				    Log.e(TAG, e.getMessage());
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("删除失败...");
				}else{
					showCustomToast("删除成功...");
					mHandler.sendEmptyMessage(3);
				}
				
				
			}

		});
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case 3:
					if(mStAdapter!=null){
						mStAdapter.deleteMsg(mPosition);
						mStAdapter.notifyDataSetChanged();
					}
					break;
			}
		}
	};
	
	public String sprintf(String format, double number) {
		return new DecimalFormat(format).format(number);
	}
	//sizeType :big,middle,small
	//type : real 或 ""
	public String avatar_file(int uid, String sizeType, String type) {
		String var = "avatarfile_" + uid + "_" + sizeType + "_" + type;
		String avatarPath = "";
			uid = Math.abs(uid);
			String struid = sprintf("000000000", uid);
			String dir1 = struid.substring(0, 3);
			String dir2 = struid.substring(3, 5);
			String dir3 = struid.substring(5, 7);
			StringBuffer avater = new StringBuffer();
			avater.append(dir1 + "/" + dir2 + "/" + dir3 + "/" + struid.substring(struid.length() - 2));
			avater.append("real".equals(type) ? "_real_avatar_" : "_avatar_");
			avater.append(sizeType + ".jpg");
			avatarPath = avater.toString();

		return avatarPath;
	}
	
}
